from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 确保Chrome驱动路径正确
chrome_driver_path = "D:/pythonProject/20250331/chromedriver.exe"  # 请根据实际路径修改

try:
    # 配置Chrome驱动路径
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")  # 可选：启动时最大化窗口

    # 初始化webdriver
    driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)

    # 打开百度首页
    driver.get("https://www.baidu.com")

    # 使用显式等待确保元素加载完成
    search_box = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, 'kw'))
    )
    search_box.send_keys('selenium')

    # 打印当前页面标题以确认是否成功打开
    print("当前页面标题:", driver.title)

except WebDriverException as e:
    print("发生错误:", e)
finally:
    # 关闭浏览器
    if 'driver' in locals():
        driver.quit()